<template>
  <div
    class="example-pie-chart"
    :id="id"
    :style="'height: ' + height + ';' + 'width: ' + width + ';'"
  ></div>
</template>

<script lang="ts">
import { defineComponent, onMounted, PropType } from "vue";
import * as echarts from "echarts";
import { ECharts, EChartsCoreOption } from "echarts";

export default defineComponent({
  name: "ExamplePieChart",
  props: {
    height: {
      type: String,
      default: "300px",
    },
    width: {
      type: String,
      default: "100%",
    },
    option: {
      type: Object as PropType<EChartsCoreOption>,
      required: true,
    },
  },
  emits: ["chartClick"],
  setup(props, context) {
    const id = Math.random().toString().substr(2);
    let myChart: ECharts;
    const echartInit = (id: string) => {
      const doc = document.getElementById(id);
      if (doc) {
        myChart = echarts.init(doc);
        // 指定图表的配置项和数据

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(props.option);
        myChart.on("click", function (params) {
          context.emit("chartClick", params);
        });
      } else {
        throw new Error("图表指定ID节点未能找到");
      }
    };
    const repaint = (newOptions: EChartsCoreOption) => {
      myChart.setOption(newOptions);
    };
    onMounted(() => {
      echartInit(id);
    });
    return {
      id,
      repaint,
    };
  },
});
</script>

<style scoped lang="scss">
.example-pie-chart {
}
</style>
